﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using VIP.Domain.Core.DomainObject;
using VIP.Infrastructure.Caching;

namespace VIP.Domain.Core.Factories
{
    public abstract class AbstractAggregateRootLoader<T> : IAggregateRootLoader<T> where T : AggregateRoot
    {
        public ICachingProvider CachingProvider { get; set; }
        public IOptions<DomainOptions> DomainOptions { get; set; }
        /// <summary>
        /// 聚合根cacheKey前缀
        /// </summary>
        public abstract string AggregateRootCachePrefix { get; }

        public async Task<T> LoadAsync(Guid id)
        {
            if (!DomainOptions.Value.LoadObjFromCache)
            {
                return await this.LoadFromDbAsync(id);
            }

            var key = $"{AggregateRootCachePrefix}{id}";
            var rel = await CachingProvider.Get<T>(key);
            if (rel == null)
            {
                rel = await this.LoadFromDbAsync(id);
            }
            return rel;
        }

        public Task<bool> Remove(Guid id)
        {
            if (!DomainOptions.Value.LoadObjFromCache)
            {
                return Task.Run(() =>
                {
                    return true;
                });
            }
            var key = $"{AggregateRootCachePrefix}{id}";
            return CachingProvider.Remove(key);
        }

        public Task<bool> Save(T obj)
        {
            if (!DomainOptions.Value.LoadObjFromCache)
            {
                return Task.Run(() =>
                {
                    return true;
                });
            }
            var key = $"{AggregateRootCachePrefix}{obj.Id}";
            return CachingProvider.SetAsync(key, obj);
        }
        public abstract Task<T> LoadFromDbAsync(Guid id);
    }
}
